#import "ARLViewUtils.h"

@implementation ARLViewUtils
//根据view发现view所在viewcontroller
+(UIViewController *)findViewController:(UIView*)view{
    id responder = view;
    while (responder){
        if ([responder isKindOfClass:[UIViewController class]]){
            return responder;
        }
        responder = [responder nextResponder];
    }
    return nil;
}

+ (void)resetAppRootViewController:(UIViewController*)viewController{
    [ARLViewUtils getRootWindow].rootViewController=viewController;
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getTopViewController{
    UIViewController *rootViewController = [ARLViewUtils getRootWindow].rootViewController;
    UIViewController *currentVC = [self getCurrentViewControllerFrom:rootViewController];
    return currentVC;
}

//获取RootViewController所在的window
+ (UIWindow*)getRootWindow{
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [UIApplication sharedApplication].windows;
        for (UIWindow *target in windows) {
            if (target.windowLevel == UIWindowLevelNormal) {
                window = target;
                break;
            }
        }
    }
    return window;
}

+ (UIViewController *)getCurrentViewControllerFrom:(UIViewController *)rootVC{
    UIViewController *currentVC;
    //看看是否有present界面，如果有，则遍历全部找出来，因为present是modal出来的，所以应该是window层级
    if ([rootVC presentedViewController]) {
        while ([rootVC presentedViewController]) {
            rootVC = [rootVC presentedViewController];
        }
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentViewControllerFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentViewControllerFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
        
    }
    
    return currentVC;
}



@end
